package edu.ynu.se.xiecheng.achitectureclass.service;

import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;


@Service
public class TokenService {

    // API配置直接写在代码中
    private static final String API_URL = "https://fbox360.com/idserver/core/connect/token";
    private static final String CLIENT_ID = "68db2e8bda8d47b5b5db7eaf71c7dcdd";
    private static final String CLIENT_SECRET = "76dc724c95004acab25482d344dab407";

    private String accessToken;
    private long tokenExpiryTime;

    // 获取token
    public String getAccessToken() {
        // 如果token有效，直接返回
        if (accessToken != null && System.currentTimeMillis() < tokenExpiryTime) {
            return accessToken;
        }

        // 否则重新获取token
        fetchNewToken();
        return accessToken;
    }

    // 获取新token
    private void fetchNewToken() {
        RestTemplate restTemplate = new RestTemplate();

        // 设置请求体
        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
        body.add("grant_type", "client_credentials");
        body.add("client_id", CLIENT_ID);
        body.add("client_secret", CLIENT_SECRET);
        body.add("scope", "fbox");

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(body, headers);

        // 发起POST请求
        ResponseEntity<String> response = restTemplate.exchange(API_URL, HttpMethod.POST, requestEntity, String.class);

        if (response.getStatusCode() == HttpStatus.OK) {
            try {
                // 解析返回的JSON
                ObjectMapper mapper = new ObjectMapper();
                JsonNode jsonNode = mapper.readTree(response.getBody());

                accessToken = jsonNode.get("access_token").asText();
                int expiresIn = jsonNode.get("expires_in").asInt();

                // 设置token过期时间
                // 设置token过期时间
                tokenExpiryTime = System.currentTimeMillis() + expiresIn * 1000L; // 直接计算毫秒数
            } catch (Exception e) {
                throw new RuntimeException("获取token失败", e);
            }
        } else {
            throw new RuntimeException("获取token时请求失败，状态码：" + response.getStatusCode());
        }
    }
}